package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.dao.BDeviceInfoMapper;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.BDeviceInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.GZIPUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author lizk
 */
@Service
@DS("upmp")
public class BDeviceInfoServiceImpl extends ServiceImpl<BDeviceInfoMapper, BDeviceInfo> implements IBDeviceInfoService {

    @Autowired
    private BDeviceInfoMapper bDeviceInfoMapper;
    @Autowired
    private BTermBrandInfoServiceImpl bTermBrandInfoService;
    @Autowired
    private BTermModelInfoServiceImpl bTermModelInfoService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpSysSeqService sysSeqService;
    @Autowired
    private IBTermModelInfoService modelInfoService;
    @Autowired
    private IBTermBrandInfoService brandInfoService;
    @Autowired
    private IBDeviceActionService deviceActionService;
    @Autowired
    private IUpmpOrganizationService organizationService;

    private String webNextUrl = "/devBindInfo";
    private long oprMenuId = 1;
    private String oprMenuName = "终端管理:终端库存管理";
    private long chkMenuId = 2;


    @Override
    public List<BDeviceInfo> getSN(String instId) {

        return bDeviceInfoMapper.findSN(instId);
    }

    @Override
    public IPage<BDeviceInfo> findByPage(QueryRequest queryRequest, BDeviceInfo bDeviceInfo) {
        try {
            LambdaQueryWrapper<BDeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(bDeviceInfo.getInstId())) {
                queryWrapper.eq(BDeviceInfo::getInstId, bDeviceInfo.getInstId());
            }
            if (!StringUtils.isEmpty(bDeviceInfo.getDeviceNo())) {
                queryWrapper.like(BDeviceInfo::getDeviceNo, bDeviceInfo.getDeviceNo());
            }
            if (!StringUtils.isEmpty(bDeviceInfo.getBrandCode())) {
                queryWrapper.eq(BDeviceInfo::getBrandCode, bDeviceInfo.getBrandCode());
            }
            if (!StringUtils.isEmpty(bDeviceInfo.getModelCode())) {
                queryWrapper.eq(BDeviceInfo::getModelCode, bDeviceInfo.getModelCode());
            }
            Page<BDeviceInfo> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, "createTime", "descend",true);

            //设置模型数量和商户名称
            Page<BDeviceInfo> infoPage = this.page(page, queryWrapper);
            for (BDeviceInfo deviceInfo : infoPage.getRecords()) {
                String brandCode = deviceInfo.getBrandCode();
                String modelCode = deviceInfo.getModelCode();

                if (StringUtils.isEmpty(brandCode) && StringUtils.isEmpty(modelCode)) {
                    BTermBrandInfo brandInfo = bTermBrandInfoService.getBrandCodeAndName(brandCode);
                    BTermModelInfo modelInfo = bTermModelInfoService.getModelName(brandCode, modelCode);
                    if (!StringUtils.isEmpty(brandInfo)) {
                        deviceInfo.setBrandName(brandInfo.getBrandName());
                    }
                    if (!StringUtils.isEmpty(modelInfo)) {
                        deviceInfo.setModelName(modelInfo.getModelName());
                    }
                }
            }

            return infoPage;
        } catch (Exception e) {
            log.error("获取语音设备信息失败", e);
            return null;
        }
    }

    @Override
    public void batchInsert(List<BDeviceInfoVO> list) throws RedpException {
        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(list.get(0).getInstId(), "deviceInfo:add");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");

        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {

            for (int i = 0; i < list.size(); i++) {
                BDeviceInfo deviceInfo = new BDeviceInfo();
                BeanUtils.copyProperties(list.get(i), deviceInfo);
                //获取品牌代码
                String deviceCode = BusinessContainer.DeviceNo_PREFIX + DateUtils.formatDate(DateUtils.currentDate(), DateUtils.FORMAT_YYYYMM)
                        + String.format("%06d", Integer.parseInt(sysSeqService.updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.DeviceNo_PREFIX, null)));

                /*入库方式*/
                deviceInfo.setLibraryType("02");
                /*设备状态*/
                deviceInfo.setStatus("10");
                deviceInfo.setCreateTime(lastUpddt);
                deviceInfo.setDeviceNo(deviceCode);
                deviceInfo.setCrtOrgId(user.getCrtOrgId());
                deviceInfo.setOprId(user.getId());

                deviceInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.save(deviceInfo);

                bizTmpService.saveBizTmp(deviceInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), oprMenuName,
                        deviceInfo.getStatus(), deviceInfo.getAuditStatus(), deviceInfo.getId(), "", null, null, null);
            }

        } else {
            for (int i = 0; i < list.size(); i++) {
                BDeviceInfo deviceInfo = new BDeviceInfo();
                BeanUtils.copyProperties(list.get(i), deviceInfo);
                //获取品牌代码
                String deviceCode = BusinessContainer.DeviceNo_PREFIX + DateUtils.formatDate(DateUtils.currentDate(), DateUtils.FORMAT_YYYYMM)
                        + String.format("%06d", Integer.parseInt(sysSeqService.updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.DeviceNo_PREFIX, null)));

                /*入库方式*/
                deviceInfo.setLibraryType("02");
                /*设备状态*/
                deviceInfo.setStatus("10");
                deviceInfo.setCreateTime(lastUpddt);
                deviceInfo.setDeviceNo(deviceCode);
                deviceInfo.setCrtOrgId(user.getCrtOrgId());
                deviceInfo.setOprId(user.getId());
                deviceInfo.setStatus(BusinessContainer.status_00);
                deviceInfo.setAuditStatus(BusinessContainer.status_02);
                this.save(deviceInfo);

                bizHisService.saveBizHisNew(deviceInfo, deviceInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        deviceInfo.getId(), null, null, null);
            }

        }
    }

    @Override
    public void updateDevice(BDeviceInfoVO bDeviceInfoVO) throws RedpException {
        if ("upd".equals(bDeviceInfoVO.getOptFlag())) {
            saveData(bDeviceInfoVO);
        } else {
            saveData1(bDeviceInfoVO);
        }

    }

    @Override
    public void createDevice(BDeviceInfoVO bDeviceInfoVO) throws RedpException {
        saveData(bDeviceInfoVO);
    }

    /**
     * 更新入库终端sn为已使用
     *
     * @param instId  银行代码
     * @param sn      终端sn
     * @param mchntNo 关联商户编码
     * @param termNo  关联虚拟终端编号
     */
    @Override
    public void updateTermSn(String instId, String sn, String mchntNo, String termNo) {

        StringBuffer sql = new StringBuffer("update T_B_DEVICE_INFO set status = '11',mchnt_no = '" + mchntNo + "',term_no = '" + termNo + "' where INST_ID = :instId and sn = :sn and audit_status not in('00','01','03') and status = '10' ");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        if (!user.isAdmin()) {
            String userOrgCodes = GZIPUtils.uncompressToString(user.getUserOrgCodes());
            String orgCodes = userOrgCodes.replaceAll(",", "','");

            orgCodes = "'" + orgCodes + "'";
            sql.append("and CRT_ORG_ID in (" + orgCodes + ") ");
            bDeviceInfoMapper.updateTermSn(instId, sn, mchntNo, termNo, orgCodes);
        } else {
            bDeviceInfoMapper.updateTermSnNoAdmin(instId, sn, mchntNo, termNo);
        }

    }

    @Override
    public Map<String, Object> snSelect2List(String q, QueryRequest request) {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");

        String sn = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            sn = param[0];
        }
        String instId = "";
        if (null != param && param.length > 1) {
            if (Common.isNotBlank(param[1])) {
                instId = param[1];
            }
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(instId)) {
            instId = user.getInstId();
        }
        try {
            LambdaQueryWrapper<BDeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.notIn(BDeviceInfo::getAuditStatus, "('00','01','03')");
            queryWrapper.eq(BDeviceInfo::getStatus, "10");
            queryWrapper.eq(BDeviceInfo::getInstId, instId);
            if (null != user && !user.isAdmin()) {
//                queryWrapper.in(BDeviceInfo::getSignInstId, Arrays.asList(GZIPUtils.uncompressToString(user.getUserOrgCodes()).split(",")));
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(sn)) {
                String finalSn = sn;
                queryWrapper.and(qw -> qw.likeRight(BDeviceInfo::getSn, finalSn));
            }
            queryWrapper.orderByDesc(BDeviceInfo::getCreateTime);
            Page<BDeviceInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<BDeviceInfo> page1 = this.page(page, queryWrapper);
            List<BDeviceInfo> listx = page1.getRecords();
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            if (listx != null) {
                for (int i = 0; i < listx.size(); i++) {
                    BDeviceInfo org = listx.get(i);
                    map = new HashMap<String, String>();
                    map.put("id", org.getSn());
                    map.put("name", org.getSn());

                    list.add(map);
                }
                maps.put("results", list);
                maps.put("total", page.getTotal());
                int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
                if (pageIndex == page1.getTotal()) {
                    maps.put("more", false);
                } else {
                    maps.put("more", true);
                }
            }
            return maps;

        } catch (Exception e) {
            log.error("获取SN信息失败", e);
            return null;
        }
    }

    private void saveData(BDeviceInfoVO bDeviceInfoVO) throws RedpException {
        String flag = bDeviceInfoVO.getOptFlag();
        String id = bDeviceInfoVO.getId();
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        BDeviceInfo entity = new BDeviceInfo();
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
//        BDeviceInfo oldEntity = null;
//        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag) ) {
//            oldEntity = this.baseMapper.selectById(id);
//        }
        //00-未使用；01-已使用；02-损毁；03-故障；04-装机出库
        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
            String deviceNo = BusinessContainer.DeviceNo_PREFIX + DateUtils.formatDate(DateUtils.currentDate(), DateUtils.FORMAT_YYYYMM)
                    + String.format("%06d", Integer.parseInt(sysSeqService.updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.DeviceNo_PREFIX, null)));

            //校验权限，是否需要审核
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:add");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                BeanUtils.copyProperties(bDeviceInfoVO, entity);
                entity.setId(null);
                entity.setDeviceNo(deviceNo);
                //         entity.setInstId(user.getInstId());
                entity.setOprId(user.getId());
                //         entity.setCrtOrgId(org.getOrgCode());
                entity.setCreateTime(lastUpddt);
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                this.save(entity);
                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), oprMenuName,
                        entity.getStatus(), entity.getAuditStatus(), entity.getId(), "", null, null, null);

            } else {
                BeanUtils.copyProperties(bDeviceInfoVO, entity);
                entity.setId(null);
                entity.setDeviceNo(deviceNo);
                entity.setOprId(user.getId());
                entity.setCreateTime(lastUpddt);
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(entity);

                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(flag)) {
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:edit");
            BeanUtils.copyProperties(bDeviceInfoVO, entity);
            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                entity.setLastOprId(user.getId());
                entity.setLastUpdateTime(lastUpddt);
                entity.setReserve6("");
                this.baseMapper.updateById(entity);
//                termEquipmentDao.updateAuditStatus(id, entity.getAuditStatus());//只修改状态
                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), oprMenuName,
                        entity.getStatus(), entity.getAuditStatus(), entity.getId(), "", null, null, null);
            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                entity.setReserve6("");
                BDeviceInfo termEquipment = this.baseMapper.selectById(id);
                BeanUtils.copyProperties(entity, termEquipment);
                this.baseMapper.updateById(entity);
                //历史表新增
                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBaseMapper().selectById(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据!");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }

            BDeviceInfo termEquipmentNew = JSON.parseObject(bizdata, BDeviceInfo.class);

            BDeviceInfo termEquipment = this.baseMapper.selectById(id);
            // 备份正式表数据
            BDeviceInfo termEquipmentOld = new BDeviceInfo();
            BeanUtils.copyProperties(termEquipment, termEquipmentOld);
            if (Common.isBlank(termEquipment) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }

            String opt = bDeviceInfoVO.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常!");
            }
            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(termEquipment.getAuditStatus())) {
                if (!PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {

                } else {
                    BeanUtils.copyProperties(termEquipmentNew, termEquipment);
                }
            } else {
                BeanUtils.copyProperties(termEquipmentNew, termEquipment);
            }

            String auditRefuseReason = bDeviceInfoVO.getAuditRefuseReason();
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(termEquipment.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termEquipment.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                } else {
                    termEquipment.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(termEquipment.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    termEquipment.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                } else {
                    termEquipment.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            termEquipment.setAuditRefuseReason(auditRefuseReason);
            this.updateById(termEquipment);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(termEquipment, termEquipment, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), oprMenuName,
                        termEquipment.getId(), null, null, null);
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(termEquipment, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(oprMenuId), oprMenuName,
                    termEquipment.getStatus(), termEquipment.getAuditStatus(), termEquipment.getId(), "", null, null, null);
        }

    }

    private void saveData1(BDeviceInfoVO bDeviceInfoVO) throws RedpException {
        String flag = bDeviceInfoVO.getOptFlag();
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        BDeviceAction deviceAction = null;
        String bizOpr = "";
        BDeviceInfo entity = null;
        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();

        if (!PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {
            String ids = bDeviceInfoVO.getIds();
            if (Common.isBlank(ids)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            String[] idArr = ids.split(",");
            if (idArr.length >= 1) {
                List<BDeviceInfo> termEquipment = new ArrayList<BDeviceInfo>();
                for (int i = 0; i < idArr.length; i++) {
                    BDeviceInfo e = this.getById(idArr[i]);
                    termEquipment.add(e);
                }

                Iterator<BDeviceInfo> it = termEquipment.iterator();
                while (it.hasNext()) {
                    entity = it.next();
                    if (Common.isBlank(entity)) {
                        log.error("根据id没有找到指定数据！");
                        throw new RedpException("根据id没有找到指定数据！");

                    }
                    BDeviceInfo oldEntity = new BDeviceInfo();
                    if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(flag)) {
                        BeanUtils.copyProperties(entity, oldEntity);
                    }
                    BDeviceInfo entityTmp = new BDeviceInfo();
                    BeanUtils.copyProperties(entity, entityTmp);
                    if ("equout".equals(flag) || "repout".equals(flag) || "cheji".equals(flag)) {
                        deviceAction = new BDeviceAction();
                        deviceAction.setId(DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS"));
                        deviceAction.setDeviceNo(entity.getDeviceNo());
                        deviceAction.setBrandCode(entity.getBrandCode());
                        deviceAction.setModelCode(entity.getModelCode());

                        BTermModelInfo termModel = modelInfoService.findTermModel(entity.getModelCode());
                        if (termModel == null) {
                            deviceAction.setModelName("");
                        } else {
                            deviceAction.setModelName(termModel.getModelName());
                        }
                        BTermBrandInfo termBrand = brandInfoService.findTermBrand(entity.getBrandCode());
                        if (termBrand == null) {
                            deviceAction.setBrandName("");
                        } else {
                            deviceAction.setBrandName(termBrand.getBrandName());
                        }
                        deviceAction.setSn(entity.getSn());
                        deviceAction.setOprId(user.getId());//登记操作人
                        deviceAction.setCrtOrgId(entity.getCrtOrgId());
                        deviceAction.setCreateTime(lastUpddt);
                        deviceAction.setLastUpdateTime(lastUpddt);
                        deviceAction.setLastOprId(user.getId());
                        deviceAction.setStatus("00");
                        deviceAction.setLeaseStartDate(entity.getLeaseStartDate());
                        deviceAction.setLeaseEndDate(entity.getLeaseEndDate());
                        deviceAction.setMchntNo(entity.getMchntNo());
                        if ("equout".equals(flag)) {//装机出库
                            bizOpr = "0";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:equout");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("14");
                                deviceAction = null;
                            } else {
                                entity.setStatus("14");
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                                deviceAction.setAction("40");
                            }
                        } else if ("repout".equals(flag)) {//维修出库
                            bizOpr = "1";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:repout");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("13");
                                deviceAction = null;
                            } else {
                                entity.setStatus("13");
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                                deviceAction.setAction("30");
                            }
                        } else if ("cheji".equals(flag)) {//撤机
                            bizOpr = "2";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:cheji");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("15");
                                deviceAction = null;
                            } else {
                                entity.setStatus("15");
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                                deviceAction.setAction("51");
                            }
                        }
                    } else if ("orgin".equals(flag) || "repin".equals(flag) || "chejiin".equals(flag)) {
                        if ("orgin".equals(flag)) {//返还入库
                            deviceAction = deviceActionService.queryDeviceAction(entity.getDeviceNo(), "40");
                            if (deviceAction == null) {
                                throw new RedpException("查不到要返还入库的数据");
                            }
                            bizOpr = "3";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:orgin");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("10");
                                entityTmp.setMchntNo(null);
                                entityTmp.setTermNo(null);
                                deviceAction = null;
                            } else {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                                entity.setStatus("10");
                                entity.setMchntNo(null);
                                entity.setTermNo(null);
                                deviceAction.setAction("42");//返还入库 修改状态
                                deviceAction.setLastUpdateTime(lastUpddt);
                                deviceAction.setLastOprId(user.getId());
                            }
                        } else if ("repin".equals(flag)) {//修复入库
                            deviceAction = deviceActionService.queryDeviceAction(entity.getDeviceNo(), "30");
                            if (deviceAction == null) {
                                throw new RedpException("查不到要修复入库的数据");
                            }
                            bizOpr = "4";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "终端库存管理:修复入库");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("10");
                                entityTmp.setMchntNo(null);
                                entityTmp.setTermNo(null);
                                deviceAction = null;
                            } else {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                                entity.setStatus("10");
                                entity.setMchntNo(null);
                                entity.setTermNo(null);
                                deviceAction = deviceActionService.queryDeviceAction(entity.getDeviceNo(), "30");
                                deviceAction.setAction("31");//修复入库 修改状态
                                deviceAction.setLastUpdateTime(lastUpddt);
                                deviceAction.setLastOprId(user.getId());
                            }
                        } else if ("chejiin".equals(flag)) {//撤机入库
                            deviceAction = deviceActionService.queryDeviceAction(entity.getDeviceNo(), "51");
                            if (deviceAction == null) {
                                throw new RedpException("查不到要撤机入库的数据");
                            }
                            bizOpr = "5";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "终端库存管理:撤机入库");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("10");
                                entityTmp.setMchntNo(null);
                                entityTmp.setTermNo(null);
                                deviceAction = null;
                            } else {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                                entity.setStatus("10");
                                entity.setMchntNo(null);
                                entity.setTermNo(null);
                                deviceAction.setAction("52");//修复入库 修改状态
                                deviceAction.setLastUpdateTime(lastUpddt);
                                deviceAction.setLastOprId(user.getId());
                            }
                        }
                    } else if ("warning".equals(flag) || "sunhui".equals(flag) || "loss".equals(flag) || "give".equals(flag)) {
                        if ("warning".equals(flag)) {//报障
                            bizOpr = "6";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:warning");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("13");
                                deviceAction = null;
                            } else {
                                entity.setStatus("13");
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                            }
                        } else if ("sunhui".equals(flag)) {//报损
                            bizOpr = "7";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:sunhui");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("12");
                                deviceAction = null;
                            } else {
                                entity.setStatus("12");
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                            }
                        } else if ("loss".equals(flag)) {//丢失
                            bizOpr = "8";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:loss");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("16");
                                deviceAction = null;
                            } else {
                                entity.setStatus("16");
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                            }
                        } else if ("give".equals(flag)) {//返还第三方
                            bizOpr = "9";
                            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(bDeviceInfoVO.getInstId(), "deviceInfo:give");
                            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entity.setReserve6(flag);
                                entityTmp.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                                entityTmp.setReserve6(flag);
                                entityTmp.setStatus("17");
                                deviceAction = null;
                            } else {
                                entity.setStatus("17");
                                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                            }
                        }
                    }
                    if (deviceAction != null) {//终端设备在装机、换机、撤机、维修等操作过程中都会登记操作记录
                        deviceAction.setInstId(entity.getInstId());
                        deviceActionService.saveOrUpdate(deviceAction);
                    }
                    this.baseMapper.updateById(entity);
                    if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                        bizTmpService.saveBizTmp(entityTmp, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(),
                                lastUpddt, String.valueOf(oprMenuId), oprMenuName, entityTmp.getStatus(), entityTmp.getAuditStatus(),
                                entityTmp.getId(), "", null, null, null);
                    } else {
//                        if (Common.isNotBlank(bizHisService.getHisBizChangeData(oldEntity, entity))) {
                            bizHisService.saveBizHisNew(entity, oldEntity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(),
                                    lastUpddt, String.valueOf(oprMenuId), oprMenuName, entity.getId(), null, null, null);
//                        }
                    }
                }
            }

        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(flag)) {
            String id = bDeviceInfoVO.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            BDeviceInfo oldEntity = new BDeviceInfo();
            entity = baseMapper.selectById(id);
            if (Common.isBlank(entity)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据");
            }
            BeanUtils.copyProperties(entity, oldEntity);
            String opt = bDeviceInfoVO.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常");
            }
            String auditRefuseReason = bDeviceInfoVO.getAuditRefuseReason();
            if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    if ("equout".equals(entity.getReserve6()) || "repout".equals(entity.getReserve6()) || "cheji".equals(entity.getReserve6())) {
                        deviceAction = new BDeviceAction();
                        deviceAction.setId(DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS"));
                        deviceAction.setDeviceNo(entity.getDeviceNo());
                        deviceAction.setBrandCode(entity.getBrandCode());
                        deviceAction.setModelCode(entity.getModelCode());
                        BTermModelInfo termModel = modelInfoService.findTermModel(entity.getModelCode());
                        if (termModel == null) {
                            deviceAction.setModelName("");
                        } else {
                            deviceAction.setModelName(termModel.getModelName());
                        }
                        BTermBrandInfo termBrand = brandInfoService.findTermBrand(entity.getBrandCode());
                        if (termBrand == null) {
                            deviceAction.setBrandName("");
                        } else {
                            deviceAction.setBrandName(termBrand.getBrandName());
                        }
                        deviceAction.setSn(entity.getSn());
                        deviceAction.setOprId(user.getId());//登记操作人
                        deviceAction.setCrtOrgId(entity.getCrtOrgId());
                        deviceAction.setCreateTime(lastUpddt);
                        deviceAction.setLastUpdateTime(lastUpddt);
                        deviceAction.setLastOprId(user.getId());
                        deviceAction.setStatus("00");
                        deviceAction.setLeaseStartDate(entity.getLeaseStartDate());
                        deviceAction.setLeaseEndDate(entity.getLeaseEndDate());
                        deviceAction.setMchntNo(entity.getMchntNo());
                        if ("equout".equals(entity.getReserve6())) {//装机出库
                            entity.setStatus("14");
                            deviceAction.setAction("40");

                        } else if ("repout".equals(entity.getReserve6())) {//维修出库
                            entity.setStatus("13");
                            deviceAction.setAction("30");
                        } else if ("cheji".equals(entity.getReserve6())) {//撤机
                            entity.setStatus("15");
                            deviceAction.setAction("51");
                        }
                    } else if ("orgin".equals(entity.getReserve6()) || "repin".equals(entity.getReserve6()) || "chejiin".equals(entity.getReserve6())) {
                        if ("orgin".equals(entity.getReserve6())) {//返还入库
                            deviceAction = deviceActionService.queryDeviceAction(entity.getDeviceNo(), "40");
                            deviceAction.setAction("42");//返还入库 修改状态
                        } else if ("repin".equals(entity.getReserve6())) {//修复入库
                            deviceAction = deviceActionService.queryDeviceAction(entity.getDeviceNo(), "30");
                            deviceAction.setAction("31");//修复入库 修改状态

                        } else if ("chejiin".equals(entity.getReserve6())) {//撤机入库
                            deviceAction = deviceActionService.queryDeviceAction(entity.getDeviceNo(), "51");
                            deviceAction.setAction("52");//修复入库 修改状态
                        }
                        deviceAction.setLastUpdateTime(lastUpddt);
                        deviceAction.setLastOprId(user.getId());
                        entity.setStatus("10");
                        entity.setMchntNo(null);
                        entity.setTermNo(null);
                    } else if ("warning".equals(entity.getReserve6()) || "sunhui".equals(entity.getReserve6()) || "loss".equals(entity.getReserve6()) || "give".equals(entity.getReserve6())) {
                        if ("warning".equals(entity.getReserve6())) {//报障
                            entity.setStatus("13");
                        } else if ("sunhui".equals(entity.getReserve6())) {//报损
                            entity.setStatus("12");
                        } else if ("loss".equals(entity.getReserve6())) {//丢失
                            entity.setStatus("16");
                        } else if ("give".equals(entity.getReserve6())) {//返还第三方
                            entity.setStatus("17");
                        }
                    }
                    entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                } else {
                    entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            if (deviceAction != null) {//终端设备在装机、换机、撤机、维修等操作过程中都会登记操作记录
                deviceAction.setInstId(entity.getInstId());
                deviceActionService.save(deviceAction);
            }
            entity.setAuditRefuseReason(auditRefuseReason);
            this.baseMapper.updateById(entity);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
//                if (Common.isNotBlank(bizHisService.getHisBizChangeData(oldEntity, entity))) {
                bizHisService.saveBizHisNew(entity, oldEntity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), oprMenuName,
                        entity.getId(), null, null, null);
//                }
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(oprMenuId), oprMenuName,
                    entity.getStatus(), entity.getAuditStatus(), entity.getId(), "", null, null, null);
        }
    }

}
